# -*- coding: utf8 -*-

from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden
from bootcamp.feeds.models import Feed
from bootcamp.activities.models import Activity, Notification
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.template.loader import render_to_string
from django.core.context_processors import csrf
import json
from django.contrib.auth.decorators import login_required
from bootcamp.decorators import ajax_required

FEEDS_NUM_PAGES = 10
CATEGORY_LIST = [("all", "所有公告"), ("zlxw", "失物招领"), \
                ("esjy", "二手交易"), ("sfc", "顺风车"), ("dpzr","店铺转让"),\
                ("zfsf", "房屋租售"), ("qzzp", "求职招聘"), \
                ("dtyx", "打听一下"), \
                ("qgsj", "情感世界"), ("jzgg", "广而告之"), \
                ("zhjy", "征婚交友"), ("xqah", "兴趣爱好"), \
                ("ttsd", "谈天说地"), ("wzzw", "网站站务"),\
                ]

def feeds(request):
    if request.user.is_authenticated():
        hide_profile = False
    else:
        hide_profile = True
    all_feeds = Feed.get_feeds()
    count = {}
    for i, j in CATEGORY_LIST:
        count[i] = all_feeds.filter(category = i).count()
    count["all"] = all_feeds.count()
    cg = "all"
    if request.GET.get("category"):
        cg = request.GET.get("category")
    if cg != "all":
        all_feeds = Feed.get_feeds(category=cg)
    up_feeds = all_feeds.filter(up = 1)[0:5]
    paginator = Paginator(all_feeds, FEEDS_NUM_PAGES)
    feeds = paginator.page(1)
    from_feed = -1
    if feeds:
        from_feed = feeds[0].id
    return render(request, 'feeds/feeds.html', {
        'feeds': feeds,
        'count': count,
        'active': cg,
        'from_feed': from_feed,
        'page': 1,
        'up_feeds': up_feeds,
        'hide_profile': hide_profile,
        'cg_list': CATEGORY_LIST
        })

def feed(request, pk):
    if request.user.is_authenticated():
        hide_profile = False
    else:
        hide_profile = True
    feed = get_object_or_404(Feed, pk=pk)
    return render(request, 'feeds/feed.html', {
        'feed': feed,
        'hide_profile': hide_profile,
        })

@ajax_required
def load(request):
    from_feed = request.GET.get('from_feed')
    page = request.GET.get('page')
    active = request.GET.get('active')
    feed_source = request.GET.get('feed_source')
    if active and active != 'all':
        all_feeds = Feed.get_feeds(from_feed, active)
    else:
        all_feeds = Feed.get_feeds(from_feed)
    if feed_source != 'all':
        all_feeds = all_feeds.filter(user__id=feed_source)
    paginator = Paginator(all_feeds, FEEDS_NUM_PAGES)
    try:
        feeds = paginator.page(page)
    except PageNotAnInteger:
        return HttpResponseBadRequest()
    except EmptyPage:
        feeds = []
    html = u''
    csrf_token = unicode(csrf(request)['csrf_token'])
    for feed in feeds:
        html = u'{0}{1}'.format(html, render_to_string('feeds/partial_feed.html', {
            'feed': feed,
            'user': request.user,
            'csrf_token': csrf_token
            })
        )
    return HttpResponse(html)

def _html_feeds(last_feed, user, csrf_token, feed_source='all'):
    feeds = Feed.get_feeds_after(last_feed)
    if feed_source != 'all':
        feeds = feeds.filter(user__id=feed_source)
    html = u''
    for feed in feeds:
        html = u'{0}{1}'.format(html, render_to_string('feeds/partial_feed.html', {
            'feed': feed,
            'user': user,
            'csrf_token': csrf_token
            })
        )
    return html

@login_required
@ajax_required
def load_new(request):
    last_feed = request.GET.get('last_feed')
    user = request.user
    csrf_token = unicode(csrf(request)['csrf_token'])
    html = _html_feeds(last_feed, user, csrf_token)
    return HttpResponse(html)

def check(request):
    last_feed = request.GET.get('last_feed')
    feed_source = request.GET.get('feed_source')
    feeds = Feed.get_feeds_after(last_feed)
    if feed_source != 'all':
        feeds = feeds.filter(user__id=feed_source)
        count = feeds.count()
        return HttpResponse(count)
    count = feeds.count()
    return HttpResponse(count)

@login_required
@ajax_required
def post(request):
    last_feed = request.POST.get('last_feed')
    user = request.user
    csrf_token = unicode(csrf(request)['csrf_token'])
    feed = Feed()
    feed.user = user
    feed.category = request.POST['category']
    post = request.POST['post']
    post = post.strip()
    if len(post) > 0:
        feed.post = post[:255]
        feed.save()
        user.profile.reputation += 3
        user.save()
    html = _html_feeds(last_feed, user, csrf_token)
    return HttpResponse(html)

def like(request):
    feed_id = request.POST['feed']
    feed = Feed.objects.get(pk=feed_id)
    user = request.user
    like = Activity.objects.filter(activity_type=Activity.LIKE, feed=feed_id, user=user)
    if like:
        user.profile.unotify_liked(feed)
        like.delete()
        user.profile.reputation -= 3
        user.save()
    else:
        like = Activity(activity_type=Activity.LIKE, feed=feed_id, user=user)
        like.save()
        user.profile.notify_liked(feed)
        user.profile.reputation += 1
        user.save()
    return HttpResponse(feed.calculate_likes())

@login_required
@ajax_required
def comment(request):
    if request.method == 'POST':
        feed_id = request.POST['feed']
        feed = Feed.objects.get(pk=feed_id)
        post = request.POST['post']
        post = post.strip()
        if len(post) > 0:
            post = post[:255]
            user = request.user
            feed.comment(user=user, post=post)
            user.profile.notify_commented(feed)
            user.profile.notify_also_commented(feed)
            user.profile.reputation += 2
            user.save()
        return render(request, 'feeds/partial_feed_comments.html', {'feed': feed})
    else:
        feed_id = request.GET.get('feed')
        feed = Feed.objects.get(pk=feed_id)
        return render(request, 'feeds/partial_feed_comments.html', {'feed': feed})

def update(request):
    first_feed = request.GET.get('first_feed')
    last_feed = request.GET.get('last_feed')
    feed_source = request.GET.get('feed_source')
    feeds = Feed.get_feeds().filter(id__range=(last_feed, first_feed))
    if feed_source != 'all':
        feeds = feeds.filter(user__id=feed_source)
    dump = {}
    for feed in feeds:
        dump[feed.pk] = {'likes': feed.likes, 'comments': feed.comments}
    data = json.dumps(dump)
    return HttpResponse(data, content_type='application/json')

@login_required
@ajax_required
def track_comments(request):
    feed_id = request.GET.get('feed')
    feed = Feed.objects.get(pk=feed_id)
    return render(request, 'feeds/partial_feed_comments.html', {'feed': feed})

def remove(request):
    try:
        feed_id = request.POST.get('feed')
        feed = Feed.objects.get(pk=feed_id)

        if feed.user == request.user or request.user.is_superuser == True:
            likes = feed.get_likes()
            parent = feed.parent
            for like in likes:
                like.delete()
            feed.delete()
            request.user.profile.reputation -= 3
            request.user.save()
            if parent:
                parent.calculate_comments()
            return HttpResponse()
        else:
            return HttpResponseForbidden()
    except Exception, e:
        return HttpResponseBadRequest()

def app_feeds(request):
    if request.user.is_authenticated():
        hide_profile = False
    else:
        hide_profile = True
    all_feeds = Feed.get_feeds()
    count = {}
    for i, j in CATEGORY_LIST:
        count[i] = all_feeds.filter(category = i).count()
    count["all"] = all_feeds.count()
    cg = "all"
    if request.GET.get("category"):
        cg = request.GET.get("category")
    if cg != "all":
        all_feeds = Feed.get_feeds(category=cg)
    up_feeds = all_feeds.filter(up = 1)[0:5]
    paginator = Paginator(all_feeds, FEEDS_NUM_PAGES)
    feeds = paginator.page(1)
    from_feed = -1
    if feeds:
        from_feed = feeds[0].id
    return render(request, 'feeds/app_feeds.html', {
        'feeds': feeds,
        'count': count,
        'active': cg,
        'from_feed': from_feed,
        'page': 1,
        'up_feeds': up_feeds,
        'hide_profile': hide_profile,
        'cg_list': CATEGORY_LIST
        })

def app_feed(request, pk):
    feed = get_object_or_404(Feed, pk=pk)
    return render(request, 'feeds/app_feed.html', {
        'feed': feed,
        'hide_profile': hide_profile,
        })
